/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.distribution.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.distribution.common.model.DistributionProd;
import com.yami.shop.distribution.common.model.DistributionProdLog;
import com.yami.shop.distribution.common.service.DistributionProdService;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author lgh on 2019/04/01.
 */
@RestController
@RequestMapping("/platform/distributionProd")
@AllArgsConstructor
@Api(tags = "平台端分销商品接口")
public class DistributionProdController {

    private final DistributionProdService distributionProdService;

    private final OfflineHandleEventService offlineHandleEventService;

    @GetMapping("/count")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:info')")
    @ApiOperation(value = "根据商品id计算分销商品数量", notes = "根据商品id获取")
    @ApiImplicitParam(name = "prodId", value = "商品id", required = true, dataType = "Long")
    public ServerResponseEntity<Integer> count(Long prodId) {
        return ServerResponseEntity.success(distributionProdService.count(new LambdaQueryWrapper<DistributionProd>()
                .eq(DistributionProd::getProdId, prodId)));
    }

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:page')")
    @ApiOperation(value = "分页查找分销商品数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "prodName", value = "商品名称", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "state", value = "分销商品状态(0:商家下架 1:商家上架 2:违规下架 3:平台审核)", required = true, dataType = "Integer")
    })
    public ServerResponseEntity<IPage<DistributionProd>> page(DistributionProd distributionProd, PageParam<DistributionProd> page,
                                                        String prodName, Integer state) {
        distributionProd.setState(state);
        IPage<DistributionProd> list = distributionProdService.distributionProdsPage(page, distributionProd, prodName);
        return ServerResponseEntity.success(list);
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:info')")
    @ApiOperation(value = "根据分销商品id查看分销商品数据", notes = "根据分销商品id获取")
    @ApiImplicitParam(name = "id", value = "分销商品id", required = true, dataType = "Long")
    public ServerResponseEntity<DistributionProd> info(@PathVariable("id") Long id) {
        DistributionProd distributionProd = distributionProdService.getById(id);
        return ServerResponseEntity.success(distributionProd);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:save')")
    @ApiOperation(value = "保存分销商品")
    public ServerResponseEntity<Void> save(@RequestBody @Valid DistributionProd distributionProd) {
        distributionProd.setShopId(Constant.PLATFORM_SHOP_ID);
        distributionProd.setModifier(SecurityUtils.getSysUser().getUserId());
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.save(distributionProd);

        distributionProdService.removeDistributionProdPoCacheByProdId(distributionProd.getProdId());
        return ServerResponseEntity.success();
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    @ApiOperation(value = "修改分销商品")
    public ServerResponseEntity<Void> update(@RequestBody @Valid DistributionProd distributionProd) {
        YamiSysUser sysUser = SecurityUtils.getSysUser();

        if (!Objects.equals(distributionProd.getShopId(), Constant.PLATFORM_SHOP_ID)) {
            // 您无权对此活动商品进行操作
            throw new YamiShopBindException("yami.activity.prod.no.auth");
        }
        distributionProd.setModifier(sysUser.getUserId());
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.updateById(distributionProd);
        distributionProdService.removeDistributionProdPoCacheByProdId(distributionProd.getProdId());
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:delete')")
    @ApiOperation(value = "根据分销商品id列表批量删除分销商品")
    @ApiImplicitParam(name = "ids", value = "分销商品ids", required = true, dataType = "Long")
    public ServerResponseEntity<Void> delete(@RequestBody List<Long> ids) {
        distributionProdService.removeByIds(ids);
        return ServerResponseEntity.success();
    }


    private void setDefaultAwardNumbers(@Valid @RequestBody DistributionProd distributionProd) {
        distributionProd.setUpdateTime(new Date());

        if (StrUtil.isBlank(distributionProd.getParentAwardNumbers())) {
            // 固定奖励
            if (Objects.equals(distributionProd.getAwardNumberSet(), 0)) {
                distributionProd.setParentAwardNumbers("0");
            } else {
                distributionProd.setParentAwardNumbers(null);
            }
        }
        if (StrUtil.isBlank(distributionProd.getAwardNumbers())) {
            distributionProd.setAwardNumbers("0");
            // 固定奖励
            if (Objects.equals(distributionProd.getAwardNumberSet(), 0)) {
                distributionProd.setAwardNumbers("0");
            } else {
                distributionProd.setAwardNumbers(null);
            }
        }
    }

    @GetMapping("/getOfflineEventByDistProdId/{distributionProdId}")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:info')")
    @ApiOperation(value = "根据分销商品id获取下线信息")
    @ApiImplicitParam(name = "distributionProdId", value = "分销商品id", required = true, dataType = "Long")
    public ServerResponseEntity<OfflineHandleEvent> getOfflineEventByDistProdId(@PathVariable("distributionProdId") Long distributionProdId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.DISTRIBUTION_PROD.getValue(), distributionProdId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    @ApiOperation(value = "下线分销商品")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        DistributionProd distributionProd = distributionProdService.getById(offlineHandleEvent.getHandleId());
        if (distributionProd == null) {
            // 未找到该分销商品信息
            throw new YamiShopBindException("yami.distribution.prod.exist.error");
        }
        distributionProdService.offline(distributionProd, offlineHandleEvent.getOfflineReason(), sysUserId);
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditDistributionProd")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    @ApiOperation(value = "分销商品审核")
    public ServerResponseEntity<Void> auditDistributionProd(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        DistributionProd distributionProd = distributionProdService.getById(offlineHandleEventAuditParam.getHandleId());
        if (distributionProd == null) {
            // 未找到该分销商品信息
            throw new YamiShopBindException("yami.distribution.prod.exist.error");
        }
        distributionProdService.auditDistributionProd(offlineHandleEventAuditParam, sysUserId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getDistributionProdLogPage")
    @ApiOperation(value = "获取分销商品记录信息")
    public ServerResponseEntity<IPage<DistributionProdLog>> getDistributionProdLogPage(DistributionProdLog distributionProdLog,
                                                                                 PageParam<DistributionProdLog> page) {
        IPage<DistributionProdLog> distributionProdLogL = distributionProdService.getDistributionProdLogPage(page, distributionProdLog);
        return ServerResponseEntity.success(distributionProdLogL);
    }
}
